// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/connectors/hive/file_handle.h>
#include <pollux/common/base/counters.h>
#include <pollux/common/base/stats_reporter.h>
#include <pollux/common/file/file_systems.h>
#include <pollux/common/time/timer.h>

#include <atomic>

namespace kumo::pollux {

uint64_t FileHandleSizer::operator()(const FileHandle& fileHandle) {
  // TODO: add to support variable file cache size support when the file system
  // underneath supports.
  return 1;
}

namespace {
// The group tracking is at the level of the directory, i.e. Hive partition.
std::string groupName(const std::string& filename) {
  const char* slash = strrchr(filename.c_str(), '/');
  return slash ? std::string(filename.data(), slash - filename.data())
               : filename;
}
} // namespace

std::unique_ptr<FileHandle> FileHandleGenerator::operator()(
    const std::string& filename,
    const FileProperties* properties,
    filesystems::File::IoStats* stats) {
  // We have seen cases where drivers are stuck when creating file handles.
  // Adding a trace here to spot this more easily in future.
  process::TraceContext trace("FileHandleGenerator::operator()");
  uint64_t elapsedTimeUs{0};
  std::unique_ptr<FileHandle> fileHandle;
  {
    MicrosecondTimer timer(&elapsedTimeUs);
    fileHandle = std::make_unique<FileHandle>();
    filesystems::FileOptions options;
    options.stats = stats;
    if (properties) {
      options.fileSize = properties->fileSize;
      options.readRangeHint = properties->readRangeHint;
      options.extraFileInfo = properties->extraFileInfo;
    }
    fileHandle->file = filesystems::getFileSystem(filename, properties_)
                           ->openFileForRead(filename, options);
    fileHandle->uuid = StringIdLease(fileIds(), filename);
    fileHandle->groupId = StringIdLease(fileIds(), groupName(filename));
    VKLOG(1) << "Generating file handle for: " << filename
            << " uuid: " << fileHandle->uuid.id();
  }
  RECORD_HISTOGRAM_METRIC_VALUE(
      kMetricHiveFileHandleGenerateLatencyMs, elapsedTimeUs / 1000);
  // TODO: build the hash map/etc per file type -- presumably after reading
  // the appropriate magic number from the file, or perhaps we include the file
  // type in the file handle key.
  return fileHandle;
}

} // namespace kumo::pollux
